from app.model.address_model import AddressModel
from app.controller.validate.address_validate import AddressPostValidate, AddressPutValidate, AddressDeleteValidate
from .shoutcut_import import *

bp = V1BluePoint('address', __name__, url_prefix='')


@bp.route('/address', methods=['POST'])
@validate_form(AddressPostValidate)
@user_require
def post_address():
    """增加一个地址"""
    uid = g.uid
    count = AddressModel.query.filter_by(user_id=uid).count()
    if count >= 5:
        return error_json(ResponseCode.OPERATOR_ERROR, errmsg='用户地址最多只能5个')
    new_address = AddressModel(request.json, g.uid)
    sqla_db.session.add(new_address)
    sqla_db.session.commit()
    return success_json({'id': new_address.id})


@bp.route('/address', methods=['PUT'])
@validate_form(AddressPutValidate)
@user_require
def put_address():
    """
    修改地址
    1. 根据要查找address的id找到address
    2. 判断找到的address是不是当前用户
    3. 更新address信息
    """
    uid = g.uid
    address_id = request.json.get('id')
    address = AddressModel.query.filter_by(id=address_id).first()
    if not address:
        return error_json(ResponseCode.RESOURCE_NOT_FOUND, errmsg='指定id地址不存在')

    if address.user_id != uid:
        return error_json(ResponseCode.RESOURCE_NOT_FOUND, errmsg='无法在当前用户找到指定id地址')

    address.update(request.json)
    sqla_db.session.commit()
    return success_json({'id': address.id})


@bp.route('/address', methods=['DELETE'])
@validate_form(AddressDeleteValidate)
@user_require
def delete_address():
    """
    删除地址
    1. 根据要查找address的id找到address
    2. 判断找到的address是不是当前用户
    3. 更新address信息
    """
    uid = g.uid
    address_id = request.json.get('id')
    address = AddressModel.query.filter_by(id=address_id).first()
    if not address:
        return error_json(ResponseCode.RESOURCE_NOT_FOUND, errmsg='指定id地址不存在')

    if address.user_id != uid:
        return error_json(ResponseCode.RESOURCE_NOT_FOUND, errmsg='无法在当前用户找到指定id地址')

    sqla_db.session.delete(address)
    sqla_db.session.commit()
    return success_json({'id': address.id})


@bp.route('/address', methods=['GET'])
@user_require
def get_address_by_uid():
    """
    获取用户地址
    1. 根据要查找address的id找到address
    2. 判断找到的address是不是当前用户
    3. 更新address信息
    """
    uid = g.uid
    all_address = AddressModel.query. \
        filter(AddressModel.user_id == uid). \
        order_by(AddressModel.id.desc()).all()
    all_address = AddressModel.to_list(all_address, hidden=AddressModel.default_hidden)
    return success_json(all_address)
